package cn.tedu.sp02.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class ItemController {

    @Autowired
    private ItemService itemService;
    @Value("${server.port}") //注入配置的端口号
    private int port;

    //获取商品列表,商品列表封装在 JsonResult 对象中,在返回给客户端
    //转换的json格式,{"code":200,"msg":"port=8001","data":商品列表数据}
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        log.info("获取订单的商品列表",orderId="+orderId");

        // 90%概率,执行随机延迟
//        if(Math.random() < 0.9){
//            //随机延迟时长[0,5000)
//            int t = new Random().nextInt(5000);
//            log.info("延迟:"+t);
//            Thread.sleep(t);
//        }

        List<Item> items = itemService.getItems(orderId);
        JsonResult r = JsonResult.ok().msg("port=" + port).data(items);
        return r;

    }

    //减少商品库存
    // {code:200,meg:减少商品库存成功,data:null}
    /*
    @RequestBody 从客户端提交的 http 协议体数据中接收
     */
    @PostMapping("/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
        itemService.decreaseNumber(items);
        return JsonResult.ok().msg("减少商品成功");

    }


}
